package com.gitee.secretopen.sso.interceptor;

import cn.chenc.framework.core.exception.CustomException;
import com.gitee.secretopen.sso.component.TokenService;
import com.gitee.secretopen.sso.db.pojo.User;
import com.gitee.secretopen.sso.exception.CustomCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 　@description: TODO
 * 　@author 陈_C
 * 　@date 2020/3/21 20:33
 *
 */
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取根据用户信息
        User user=tokenService.getAdminLoginUser(request);
        if(user!=null){
            //用户不为空，说明还是登录状态，对登录状态进行续时
            String token=tokenService.getAdminToken(request);
            String userKey=tokenService.getAdminTokenKey(token);
            tokenService.refreshToken(userKey,user);
            return true;
        }
        //token失效，说明登录过期
        throw new CustomException(new CustomCode(false,401,"token失效"));
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
